﻿using YK.Cache.Abstractions;
using YK.Cache.Consts;
using YK.Console.Business.PermissionGroupApis;

namespace YK.Console.Business.UserStaffRoles;

internal class SaveUserStaffRoleHandler(IRepository<UserStaffRole> _repo,ICacheManager _cache,ICurrentUser _currentUser) : IRequestHandler<SaveUserStaffRoleRequest, bool>
{
    public async Task<bool> Handle(SaveUserStaffRoleRequest request, CancellationToken cancellationToken)
    {
        await _repo.DeleteAsync(x => x.UserStaffId == request.UserStaffId, cancellationToken);

        if (request.RoleIds.Any())
        {
            var roleMenuRoutes = request.RoleIds.Select(x => new UserStaffRole
            {
                UserStaffId = request.UserStaffId,
                RoleId = x
            }).ToList();

            await _repo.AddRangeAsync(roleMenuRoutes, cancellationToken);
        }

        var key = CacheConsts.GetKey<ApiPermissionDataScope>(_currentUser.TenantId, request.UserStaffId);
        await _cache.RemoveAsync(key, cancellationToken);

        return true;
    }
}
